package com.platform.modules.sys.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.platform.common.annotation.SysLog;
import com.platform.common.enumstatus.SystemEnum;
import com.platform.common.page.PageUtil;
import com.platform.common.utils.RestResponse;
import com.platform.common.validator.ValidatorUtils;
import com.platform.modules.sys.entity.SysDictEntity;
import com.platform.modules.sys.entity.SysOrgUserEntity;
import com.platform.modules.sys.entity.SysRoleEntity;
import com.platform.modules.sys.entity.SysUserEntity;
import com.platform.modules.sys.service.SysDictService;
import com.platform.modules.sys.service.SysOrgUserService;
import com.platform.modules.sys.service.SysRoleMenuService;
import com.platform.modules.sys.service.SysRoleOrgService;
import com.platform.modules.sys.service.SysRoleService;
import com.platform.modules.sys.service.SysUserService;

/**
 * 角色管理
 *
 * @author 肖亮
 */
@Api(tags = "SysRoleController|角色管理")
@RestController
@RequestMapping("/sys/role")
public class SysRoleController extends AbstractController {
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private SysRoleMenuService sysRoleMenuService;
	@Autowired
	private SysRoleOrgService sysRoleOrgService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysOrgUserService sysOrgUserService;
	/**
	 * 角色列表
	 *
	 * @param params
	 *            查询参数
	 * @return RestResponse
	 */
	@ApiOperation(value = "查询角色列表", notes = "查询角色列表")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType = "query", name = "currPage", value = "当前页数", dataType = "Integer"),
		@ApiImplicitParam(paramType = "query", name = "limit", value = "分页步数", dataType = "Integer"),
		@ApiImplicitParam(paramType = "query", name = "roleName", value = "角色名称", dataType = "String"),
		@ApiImplicitParam(paramType = "query", name = "roleCode", value = "角色编号", dataType = "String"),
		@ApiImplicitParam(paramType = "query", name = "useStatus", value = "使用状态", dataType = "String")
    })
	@PostMapping("/list")
	//@RequiresPermissions("sys:role:list")
	public RestResponse list(Integer currPage,Integer limit,String roleName,String roleCode,String useStatus, String deptId) {
		
 
//		String useStatusValue = "";
//		if(useStatus != null && !"".equals(useStatus)){
//			SysDictEntity sysDictEntity = sysDictService.getById(useStatus);
//			if(sysDictEntity != null){
//				useStatusValue = sysDictEntity.getValue();
//			}
//		}
		Map<String, Object> params = new HashMap<String,Object>();
			params.put("roleName", roleName);
			params.put("roleCode", roleCode);
			params.put("useStatus", useStatus);
			// 如需数据权限，在参数中添加DataScope
			params.put("dataScope", getDataScope());
			params.put("page", PageUtil.getCurrPage(currPage));
			params.put("limit", PageUtil.getLimit(limit));
			params.put("code", 0);
			params.put("orgNo",getOrgNo());
			params.put("deptId",deptId);
		  IPage page = sysRoleService.queryPage(params);
		return RestResponse.success().put("page", page);
		
	}

	/**
	 * 角色列表
	 *
	 * @return RestResponse
	 */
	@ApiOperation(value = "查询角色列表", notes = "查询角色列表")
	@ApiImplicitParams({
   
    })
	@PostMapping("/select")
	//@RequiresPermissions("sys:role:select")
	public RestResponse select() {
		Map<String, Object> params = new HashMap<>(2);
		params.put("dataScope", getDataScope());

		List<SysRoleEntity> list = sysRoleService.selectListByMap(params);

		return RestResponse.success().put("list", list);
	}

	/**
	 * 根据主键查询详情
	 *
	 * @param roleId
	 *            主键
	 * @return RestResponse
	 */
	@ApiOperation(value = "根据主键查询详情", notes = "根据主键查询详情")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType = "query", name = "roleId", value = "角色id", dataType = "String")
    })
	@PostMapping("/info/{roleId}")
	//@RequiresPermissions("sys:role:info")
	public RestResponse info(@PathVariable("roleId") String roleId) {
		SysRoleEntity role = sysRoleService.getById(roleId);

		// 查询角色对应的菜单
		List<String> menuIdList = sysRoleMenuService.queryMenuIdList(roleId);
		role.setMenuIdList(menuIdList);

		// 查询角色对应的机构
		List<String> orgNoList = sysRoleOrgService.queryOrgNoList(roleId);
		role.setOrgNoList(orgNoList);

		return RestResponse.success().put("role", role);
	}

	/**
	 * @param role
	 * @return RestResponse
	 */
	@ApiOperation(value = "保存角色，同机构下面角色不能重复", notes = "保存角色，同机构下面角色不能重复")
	@SysLog("保存角色")
	@PostMapping("/save")
	public RestResponse save(SysRoleEntity role) {
		
		String userId = getUserId();
		String roleCode = role.getRoleCode(); //角色编码
		if(roleCode != null && !"".equals(roleCode)){
			Map<String, Object> params = new HashMap<String,Object>();
			params.put("roleCode", roleCode);
			params.put("orgNo", getOrgNo());
			List<String> roleIdList = sysRoleService.queryRoleIdList(params);
			if(roleIdList !=null && roleIdList.size()>0){
				return RestResponse.error("角色编码不能重复");
			}
		}else{
			return RestResponse.error("角色编码不能为空");
		}
		
		ValidatorUtils.validateEntity(role);

		role.setCreateUserId(getUserId());
		role.setCreateUserOrgNo(getOrgNo());
		role.setOrgNo(getOrgNo());
		sysRoleService.add(role,userId);
		

		return RestResponse.success();
	}
	
	/**
	 * 角色启用/禁用切换
	 *
	 * @param role
	 *            role
	 * @return RestResponse
	 */
	@ApiOperation(value = "角色启用/禁用切换", notes = "角色启用/禁用切换")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType = "query", name = "roleId", value = "角色id", dataType = "String")
    })
	@SysLog("角色启用/禁用切换")
	@PostMapping("/updateUseStatus")
	//@RequiresPermissions("sys:role:update")
	public RestResponse updateUseStatus(String roleId) {
		String userId = getUserId();
		SysRoleEntity role = sysRoleService.getById(roleId);
	    if(role != null){
	    	String useStatus = role.getUseStatus();
	    	//0表示启用状态
	    	if(SystemEnum.roleStatus.ON.getKey().equals(useStatus)){
	    		ValidatorUtils.validateEntity(role);
	    		List<String> menuIdList = sysRoleMenuService.queryMenuIdList(roleId);
	    		if(menuIdList != null && menuIdList.size()>0){
	    			role.setMenuIdList(menuIdList);
	    		}
	    		role.setUseStatus(SystemEnum.roleStatus.OFF.getKey());
	    		sysRoleService.update(role,userId);
	    		//1表示禁用状态
	    	}else if(SystemEnum.roleStatus.OFF.getKey().equals(useStatus)){
	    		ValidatorUtils.validateEntity(role);
	    		List<String> menuIdList = sysRoleMenuService.queryMenuIdList(roleId);
	    		if(menuIdList != null && menuIdList.size()>0){
	    			role.setMenuIdList(menuIdList);
	    		}
	    		role.setUseStatus(SystemEnum.roleStatus.ON.getKey());
	    		sysRoleService.update(role,userId);
	    	}
	    }

		return RestResponse.success();
	}

	/**
	 * 修改角色
	 *
	 * @param role
	 *            role
	 * @return RestResponse
	 */
	@ApiOperation(value = "修改角色", notes = "修改角色")
	@SysLog("修改角色")
	@PostMapping("/update")
	//@RequiresPermissions("sys:role:update")
	public RestResponse update(SysRoleEntity role) {
		
		String userId = getUserId();
		
		ValidatorUtils.validateEntity(role);
		role.setCreateUserId(userId);
		role.setCreateUserOrgNo(getOrgNo());
		sysRoleService.update(role,userId);

		return RestResponse.success();
	}

	/**
	 * 删除角色
	 *
	 * @param roleIds
	 *            roleIds
	 * @return RestResponse
	 */
	@ApiOperation(value = "删除角色", notes = "根据roleId删除模型（支持多roleId删除）")
	@SysLog("删除角色")
	@PostMapping("/delete")
	//@RequiresPermissions("sys:role:delete")
	public RestResponse delete(String[] roleIds) {
		sysRoleService.deleteBatch(roleIds);

		return RestResponse.success();
	}
	
	
	/**
	 * 当前登录企业获取的角色
	 * @return RestResponse
	 */
	@ApiOperation(value = "当前登录企业获取的角色", notes = "当前登录企业获取的角色")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType = "query", name = "roleName", value = "角色名称", dataType = "String")
    })
	@PostMapping("/landList")
	public RestResponse landList(String roleName,Integer currPage,Integer limit){
		  String orgType = "";
		  SysUserEntity  user = this.getUser();
		if(user != null && user.getUserId() != null){
			SysUserEntity sysUserEntity = sysUserService.getById(user.getUserId());
			if(sysUserEntity != null && SystemEnum.accountType.ORG.getKey().equals(sysUserEntity.getAccountType())){
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("userId", sysUserEntity.getUserId());
				List<SysOrgUserEntity> orgUserList = sysOrgUserService.queryAll(params);
				if(orgUserList !=null && orgUserList.size()>0){
					orgType = orgUserList.get(0).getOrgType();
				}
			}
		}
		
		Map<String, Object> params = new HashMap<String,Object>();
			params.put("page", PageUtil.getCurrPage(currPage));
			params.put("limit", PageUtil.getLimit(limit));
			params.put("roleName", roleName);
			params.put("roleOrgType", orgType);
			params.put("useStatus", "1");
		IPage page = sysRoleService.queryPage(params);
	   return RestResponse.success().put("page", page);
		
	}
	
	/**
	 * 获取资质人员角色
	 * @return RestResponse
	 */
	@ApiOperation(value = "获取资质人员角色", notes = "当前登录企业获取的角色")
	@PostMapping("/auditRoleList")
	public RestResponse auditRoleList() {
		Map<String, Object> params = new HashMap<String,Object>();
			params.put("roleName", "资质");
		  List<SysRoleEntity> roleList = sysRoleService.selectListByMap(params);
		  
		return RestResponse.success().put("list", roleList);
		
	}
	
	
	
	
}
